<template>
    <div>
         <!-- 面包屑导航 -->
       <el-breadcrumb separator-class="el-icon-arrow-right">
           <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
           <el-breadcrumb-item>商品管理</el-breadcrumb-item>
           <el-breadcrumb-item>添加商品</el-breadcrumb-item>
       </el-breadcrumb>
       <el-card>
           <!-- 消息提示 -->
           <el-alert title="添加商品信息" type="info" center :closable="false"
            show-icon></el-alert>
        <!-- 步骤条 -->
        <el-steps :space="200" align-center :active="activeIndex-0" finish-status="success">
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="视频内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>
        <!-- 竖向标签栏 -->
        <el-form :rules='addGoodsRules' label-position="top" ref='addGoodsFormRef' :model="addGoodsForm" label-width="80px">
         <el-tabs tab-position="left"  v-model="activeIndex" :before-leave='changeTab' @tab-click='handleClick'>
            <el-tab-pane label="基本信息" name="0">
                <el-form-item label="商品名称" prop='goods_name'>
                  <el-input v-model="addGoodsForm.goods_name"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" prop='goods_price'>
                  <el-input type='number' v-model="addGoodsForm.goods_price"></el-input>
                </el-form-item>
                <el-form-item label="商品重量" prop='goods_weight'>
                  <el-input type='number' v-model="addGoodsForm.goods_weight"></el-input>
                </el-form-item>
                <el-form-item label="商品数量" prop='goods_number'>
                  <el-input type='number' v-model="addGoodsForm.goods_number"></el-input>
                </el-form-item>
                <el-form-item label="商品分类">
                   <el-cascader
                    v-model="categoryKey"
                    :options="categoryList"
                    :props="addCateObj"
                    @change="handleChange">
                </el-cascader>
                </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品参数" name="1">
                <el-form-item :label="item.attr_name"  v-for='item in goodsParams' :key='item.attr_id'>
                     <el-checkbox-group v-model="item.attr_vals" size="small">
                        <el-checkbox :label="val" border v-for='(val,index) in item.attr_vals' :key='index'></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name="2">
                    <el-form-item :label="item.attr_name" v-for='item in goodsStaticList' :key='item.attr_id'>
                      <el-input v-model="item.attr_vals"></el-input>
                    </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name="3">
                <el-upload
                    class="upload-demo"
                    action="http://www.klxin.cn:8888/api/private/v1/upload"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    list-type="picture"
                    :headers='headersObj'
                    :on-success='successUpload'
                    >
                    <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
              <div class="edit_container">
                <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
                <el-button type="primary" class="btnAdd" @click='addGoods'>添加商品</el-button>
                </div>
            </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    </div>
</template>

<script>
import _ from 'lodash'
export default {
  data () {
    return {
      activeIndex: '0',
      addGoodsForm: {
        goods_name: '',
        goods_cat: '',
        goods_price: 1,
        goods_number: 1,
        goods_weight: 10,
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      //   商品分类显示的id数组
      categoryKey: [],
      cateId: 0,
      //   商品分类列表
      categoryList: [],
      //   商品动态参数列表
      goodsParams: [],
      //   静态属性列表
      goodsStaticList: [],
      //   多选框选中状态
      isFlag: true,
      // 富文本内容
      editorOption: {},
      // 富文本内容
      content: '',
      addCateObj: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      //   图片上传请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      addGoodsRules: {
        goods_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请选择价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请选择重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请选择数量', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCategory()
    this.handleChange()
  },
  methods: {
    // 获取一级和二级商品分类
    async getCategory () {
      const data = await this.$http.get('categories', {
        params: { type: 3 }
      })
      this.categoryList = data.data
    },
    //   改变商品分类选择时触发事件
    handleChange () {
      if (this.categoryKey.length !== 3) {
        // 如果不是三级就为空
        this.categoryList = []
        return false
      } else {
        this.addGoodsForm.goods_cat = this.categoryKey
        this.cateId = this.categoryKey[2]
      }
    },
    // 检测是否符合数据标准
    changeTab (activeName, oldName) {
      if (this.addGoodsForm.goods_price < 0) {
        return false
      } else if (this.addGoodsForm.goods_number < 1) {
        return false
      } else if (this.addGoodsForm.goods_weight < 0) {
        return false
      } else if (this.categoryKey.length !== 3 && oldName === '0') {
        this.$message.error('请先选择商品分类')
        return false
      } if (this.addGoodsForm.goods_name.trim() === '') {
        return false
      }
    },
    // 获取商品参数请求
    async handleClick () {
      if (this.activeIndex === '1') {
        this.getGoodsParams('many')
      } else if (this.activeIndex === '2') {
        const data = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        console.log(data.data)
        this.goodsStaticList = data.data
      }
    },
    // 获取参数函数
    async getGoodsParams (val) {
      const data = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: val }
      })
      data.data.forEach(item => {
        if (item.attr_vals.length === 0) {
          item.attr_val = []
        } else {
          item.attr_vals = item.attr_vals.split(' ')
        }
      })
      console.log(data.data)
      this.goodsParams = data.data
    },
    // 点开图片预览功能
    handlePreview () {},
    // 图片移除功能
    handleRemove (file) {
    //   查询删除的图片的地址
      const path = file.response.data.tmp_path
      const index = this.addGoodsForm.pics.findIndex(item => {
        return item.pic === path
      })
      this.addGoodsForm.pics.splice(index, 1)
    },
    // 图片上传成功钩子函数
    successUpload (response, file) {
      this.$message.success('图片上传成功')
      const picInfo = { pic: response.data.tmp_path }
      this.addGoodsForm.pics.push(picInfo)
    },
    // 添加商品
    addGoods () {
      this.$refs.addGoodsFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('表单验证未通过')
        } else {
          // 深拷贝添加商品对象
          const addForm = _.cloneDeep(this.addGoodsForm)
          // 将数组转化为字符串
          addForm.goods_cat = addForm.goods_cat.join(',')
          // 将attrs添加
          // 动态参数
          this.goodsParams.forEach(item => {
            addForm.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') })
          })
          // 静态属性
          this.goodsStaticList.forEach(item => {
            addForm.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals })
          })
          // 发送添加商品请求
          const data = await this.$http.post('goods', addForm)
          console.log(data)
          if (data.meta.status === 201) {
            this.$message.success('添加商品成功')
          } else {
            return this.$message.error(data.meta.msg)
          }
        }
      })
    }
  }
}

</script>

<style lang="less" scoped>
.el-steps {
    margin:15px 0;
}
.el-input-number {
    width:100%;
}
.el-checkbox {
    margin: 0 15px 0 0 !important;
}
/deep/.ql-container {
  min-height: 150px;
}
.btnAdd {
  margin-top:20px;
}
</style>
